package cn.itsub;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

import cn.itsub.sodo.core.types.Vec2;

public class TestProgressSector {
	/**
	 * 两点之间的角度，Y轴递增方向为0度，顺时针递增，无限接近360但不包含360
	 * 
	 * @param x1
	 * @param y1
	 * @param x2
	 * @param y2
	 * @return
	 */
	public static double dir(double x1, double y1, double x2, double y2) {
		double len_x = x2 - x1;
		double len_y = y2 - y1;
		double radian = Math.atan2(len_y, len_x);// 弧度
		double a = radian * 180 / Math.PI;// 角度
		return a<0? 360+a:a;
	}
	/**
	 * 
	 * @param image
	 * @param mid	扇形圆心点百分比，左上角(0,0)，中心(0.5,0.5)
	 * @param startDeg 起始角度，水平向右为0度
	 * @param deg 从起始角度开始显示多少度
	 * @param ccw 是否逆时针，默认false代表顺时针
	 * @param show true：逐渐显示，false：逐渐隐藏
	 * @return
	 */
	public static BufferedImage shan(BufferedImage image, Vec2 mid, float startDeg, float deg, boolean ccw, boolean mode) {
		
		
		int w = image.getWidth();
		int h = image.getHeight();
		BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
		if(deg==0){
			return bufferedImage;
		}
		startDeg %= 360;
		deg %= 360;
		if (deg==0) {
			bufferedImage.getGraphics().drawImage(image, 0, 0,null);
			return bufferedImage;
		}
		
		for (int j1 = 0; j1 < h; j1++) {
			for (int j2 = 0; j2 < w; j2++) {
				int x = j2;
				int y = j1;
				int rgb = image.getRGB(x, y);
				double d = dir(w*mid.x, h*mid.y, x, y);
				if(ccw){//逆时针
					d = 360-d;
				}
				int alpha = 0;
				boolean ok = (d>=startDeg&&d<=startDeg+deg)||((startDeg+deg)>360&&d<(startDeg+deg)%360);
				if(!mode)ok=!ok;
				alpha = ok? 254 : 0;
				rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
				bufferedImage.setRGB(x, y, rgb);
			}
		}
		return bufferedImage;
	}

	public static void main(String[] args) {
		
		System.out.println( dir(32, 32, 64, -64) );
		init();
	}
	
	public static void init(){
		final JFrame fr = new JFrame();
		fr.setSize(800, 600);
		fr.setVisible(true);
		fr.setLocationRelativeTo(null);

		final JPanel jp = new JPanel() {
			float deg = 0;
			public void paint(Graphics g) {
				super.paintComponent(g);
				BufferedImage image;
				try {
					image = ImageIO.read(new File("D:/data/三国截图/QQ截图20201015001643.png"));
					deg+=1;
					g.drawImage(shan(image,new Vec2(0.5f,0.5f),270,deg,false,false), 10, 10, null);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		};

		new Timer().schedule(new TimerTask() {
			public void run() {
				jp.repaint();
			}
		}, 0, 1);

		fr.setContentPane(jp);
		fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
}
